<?php


namespace app\api\controller;

use app\api\model\MeetCheckModel;
use app\api\model\MeetModel;
use app\api\model\MeetNoticeModel;
use app\api\model\MeetTopicModel;
use app\api\model\MeetTypeModel;
use app\api\model\MeetUserModel;
use app\api\model\room\RoomOrderModel;
use app\api\model\room\RoomTimesModel;
use app\api\model\room\RoomWeekModel;
use app\api\model\TopicTopModel;
use app\common\controller\Api;
use think\Db;
use think\Exception;

class MeetTopic extends Api
{
// 无需登录的接口,*表示全部
    protected $noNeedLogin = ['cate'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    //参与人的议题详情列表
    public function lists3()
    {

    }

    //个人议题列表
    public function mylists()
    {
        $user = $this->auth->getUserinfo();
        $limit = input('limit') ? input('limit') : '15';
        $map = [];
        if (!empty(input('status'))) {
            $map = [
                'status' => input('status'),
            ];
        }
        $meet_id = input('meet_id');

        $model = MeetModel::get($meet_id);
        if (!$model) {
            $this->error('会议不存在');
        }
        $map['meet_id'] = input('meet_id');
        $map['user_id'] = $user['id'];
        $userIds = $this->auth->id;
        $model['auth_id'] = $userIds;
        $list = MeetTopicModel::where($map)->whereNull('deletetime')
            ->field('id,user_id,files,content,createtime,status,updatetime')
            ->order("id desc")
            ->paginate($limit)->each(function ($item, $key) use (&$model) {
                $check_type = 'topic';
                $checkList= MeetCheckModel::where("topic_id", "in", $item['id'])
                    //->where('type',$check_type)
                    ->field("id,status,user_id,content,files,createtime")
                    ->order("id desc")
                    ->select();
                $check_ids = $model['check_ids'];
                $check_ids_arr = explode(',',$check_ids);
                foreach ( $checkList  as $k => &$val) {
                    $user = \app\common\model\User::get($val['user_id']);
                    $username = $user?$user['nickname']:'';
                    $check_status = $val['status'] == 1?'通过':'驳回';
                    if(in_array($val['user_id'],$check_ids_arr) && $val['status']==1){
                        $check_status = '同意上会';
                    }
                    $val['check_text'] = $username.' '.$check_status;
                    $val['check_status'] = $val['status'];
                    $val['nickname'] = $username;
                    $val['status_name'] = $val['status'] == 1?"通过":"不通过";
                }
                if(empty($checkList)){
                    $checkList = [
                        ['status' => 2,'check_text' => '待审核','content' => '','createtime_text' => date('Y-m-d H:i',$item['createtime'])]
                    ];
                }
                if($item['status'] == 2 && !empty($checkList)){
                    $checkList = collection($checkList)->toArray();
                    array_push($checkList, ['status' => 0,'check_text' => '已提交，等待审核','content' => '','createtime_text' => date('Y-m-d H:i',$item['updatetime'])]);
                }
                $item['check'] = $checkList;
                $user = $this->auth->getUser();

                if($model['role_type'] == 4){
                    $map = [
                        'user_id' => $user['id'],
                        'type' =>$check_type,
                        'topic_id' => $item['id'],
                        'status' => ['<',2],
                    ];
                    $row = MeetCheckModel::where($map)
                        ->field("id")
                        ->find();
                }else{
                    $map = [
                        'user_id' => $user['id'],
                        'type' =>$check_type,
                        'topic_id' => $item['id'],
                    ];
                    $row = MeetCheckModel::where($map)
                        ->field("id")
                        ->find();
                }
                //参与人对议题今夕表决 1= 未表决 0= 已表决
                $item['is_check'] = $row?0:1;
                $item['createtime_text'] = date('Y-m-d H:i',$item['createtime']);
                return $item;
            })->toArray();
        $this->success('成功', $list);
        $this->success('成功','');
    }

    // 审核列表
    public function lists()
    {
        $limit = input('limit') ? input('limit') : '15';
        $map = [];
        if (!empty(input('status'))) {
            $map = [
                'status' => input('status'),
            ];
        }
        $meet_id = input('meet_id');

        $model = MeetModel::get($meet_id);
        if (!$model) {
            $this->error('会议不存在');
        }

        $is_boss = $model['check_ids'] == $this->auth->id;
        if ($is_boss) {
            # 校长说他只看秘书预检通过的
            $map['pre_check'] = 1;
        }

        $map['meet_id'] = input('meet_id');
        $userIds = $this->auth->id;
        $model['auth_id'] = $userIds;
        $type = input('check_type');
        if(($model['is_yiti'] == 1 || $model['is_faqi'] == 1) && $type == 'vote'){
            $map['user_id'] = $this->auth->id;
        }
        $model['is_xiaozhang'] = $model['is_xiaozhang'];
        $list = MeetTopicModel::where($map)->whereNull('deletetime')
            ->order("id desc")
            ->paginate($limit)->each(function ($item, $key) use (&$model) {
                $item['user'] = MeetUserModel::where("id", "in", $item['user_id'])->field("id,nickname,username,avatar")->find();
                $type = input('check_type');
                if($type == 'vote'){
                    $check_type = 'vote'; //查询参与人表决记录
                }else{
                    $check_type = 'topic'; //查询校长审核记录
                }
                $checkList= MeetCheckModel::where("topic_id", "in", $item['id'])
                    ->where('type',$check_type)
                    ->field("id,status,user_id,content,files,createtime")
                    ->order("id desc")
                    ->select();
                foreach ( $checkList  as $k => &$val) {
                    $user = \app\common\model\User::get($val['user_id']);
                    $username = $user?$user['nickname']:'';
                    $check_status = $val['status'] == 1?'通过':'驳回';
                    $val['check_text'] = $username.$check_status;
                    $val['check_status'] = $val['status'];
                    $val['nickname'] = $username;
                    $val['status_name'] = $val['status'] == 1?"通过":"不通过";
                }
                $item['check'] = $checkList;
                $user = $this->auth->getUser();
                $item['is_xiaozhang'] = $model['is_xiaozhang'];
                if($model['role_type'] == 4){
                    $map = [
                        'user_id' => $user['id'],
                        'type' =>$check_type,
                        'topic_id' => $item['id'],
                        'status' => ['<',2],
                    ];
                    $row = MeetCheckModel::where($map)
                        ->field("id")
                        ->find();
                }else{
                    $map = [
                        'user_id' => $user['id'],
                        'type' =>$check_type,
                        'topic_id' => $item['id'],
                    ];
                    $row = MeetCheckModel::where($map)
                        ->field("id")
                        ->find();
                }
                //参与人对议题今夕表决 1= 未表决 0= 已表决
                $item['is_check'] = $row?0:1;
                if($item['user_id'] == $model['auth_id'] ){
                    $item['is_check'] = 0;
                }
                $action = [];
                if ($item['status'] == 2) {
                    if (in_array($model['auth_id'], explode(",", $model['check_ids']))) {
                        $action['is_pass_topic'] = 1;
                        $action['is_pass_topic_str'] = "通过";
                        $action['is_reject_topic'] = 1;
                        $action['is_reject_topic_str'] = "驳回";
                    }
                }
                if ( $model['auth_id'] ==  $model['user_id'] ) {
                    $action['is_edit_topic'] = 1;
                    $action['is_edit_topic_str'] = "修改";
                }
                $item['status_name'] = getTopicStatusName($item['status']);
                $item['action']   = $action;
                return $item;
            })->toArray();
        $this->success('成功', $list);
    }


    //设置议题顶置
    public function setTop()
    {
        $id = input('id');
        $topic = MeetTopicModel::get($id);
        if(!$topic){
            $this->error('议题不存在');
        }
        $is_top = (int)input('is_top') == 1?1:0;
        $topic->is_top = $is_top;
        if($is_top==1){
            $topic->updatetime = time();
        }
        $topic->save();
        $this->success('设置成功',['is_top' => $is_top]);
    }

    //设置人员顶置
    public function setUserTop()
    {
        $id = input('id');
        if(empty($id)){
            $this->error('列表id必传');
        }
        $row = TopicTopModel::get($id);
        if(!$row){
            $this->error('id错误');
        }
        $is_top = (int)input('is_top') == 1?1:0;
        $row->is_top = $is_top;
        if($is_top==1){
            $row->updatetime = time();
        }
        $row->save();
        $this->success('设置成功',['is_top' => $is_top]);
    }

    // 审核列表
    public function newLists()
    {
        $meet_id = input('meet_id');
        $model = MeetModel::get($meet_id);
        if (!$model) {
            $this->error('会议不存在');
        }
        $loginUser = $this->auth->getUserinfo();
        $list = TopicTopModel::saveUser($model,$loginUser);

        $new1 = [];
        $i=0;
        foreach($list as &$v){
            $user = \app\common\model\User::where('id',$v['user_id'])->field('id,nickname,avatar')->find();
            $v['nickname'] = $user?$user['nickname']:'';
            $v['avatar'] = $user?$user['avatar']:'';
            $map = [
                'meet_id' => input('meet_id'),
                'user_id' => $v['user_id'],
                'is_top' => 1,
            ];
            $lists = MeetTopicModel::getUserlist($map,$loginUser,$model);
            //print_R($lists);
            $v['list'] = $lists;
            if(!empty($lists)){
                //echo $i.PHP_EOL;
                $new1[$i] = $v;
                $i++;
            }
        }

        $new2 = [];
        $i=0;
        foreach($list as &$v){
            $user = \app\common\model\User::where('id',$v['user_id'])->field('id,nickname,avatar')->find();
            $v['nickname'] = $user?$user['nickname']:'';
            $v['avatar'] = $user?$user['avatar']:'';
            $map = [
                'meet_id' => input('meet_id'),
                'user_id' => $v['user_id'],
                'is_top' => 0,
            ];
            $lists = MeetTopicModel::getUserlist($map,$loginUser,$model);
            //print_R($lists);
            $v['list'] = $lists;
            if(!empty($lists)){
                //echo $i.PHP_EOL;
                $new2[$i] = $v;
                $i++;
            }
        }
        $list = array_merge($new1,$new2);
        $this->success('成功',$list);
    }

    //设置议题顺序
    public function setSort()
    {
        $meet_id = input('meet_id');
        $model = MeetModel::get($meet_id);
        if (!$model) {
            $this->error('会议不存在');
        }
        $model->set_sort = input('set_sort');
        $model->save();
        $map = [
            'meet_id' => $meet_id,
            'status' => 1,
        ];
        $list = MeetTopicModel::where($map)->field('id,user_id')->group('user_id')->select();
        $list = collection($list)->toArray();
        //党总支会议，发给所有人
        $ids_arr = array_column($list,'user_id');

        $news = [];
        $news['from_id'] = $model['user_id'];
        $news['meet_id'] = $model['id'];
        $news['room_id'] = $model['room_id'];
        //$news['topic_id'] = $topic['id'];
        $news['link_id'] = $model['id'];

        $news['type'] = 'topic_sort';
        $news['status'] = 1; //状态:1=审批通过,2=待审批，3.审批驳回，0=删除
        $news['start_time'] = date("Y-m-d H:i:s");

        //给发布人发消息
        //给所有会议参与人发审核通过消息
        $touser = MeetUserModel::where("id", "in", $ids_arr)->select();
        $toArr = array_column($touser, 'username');
        $news['user_id'] = implode(',',$ids_arr);
        $news['user'] = implode(',', $toArr);
        $news['title'] = "议题顺序：" ;
        $news['content'] = input('set_sort') ;
        $modelN = new MeetNoticeModel($news);
        $modelN->allowField(true)->save();
        $arr = [
            'meet_id' => $meet_id,
            'title' => $news['title'],
            'description' => $news['content'],
            'url' => request()->domain().'/#/pages/tabbar-1-detial/meetingDetails/meetingDetails?id='.$news['link_id']
        ];
        $res = Wechat::sendMessage($arr, $toArr);
        $this->success('设置成功','');
    }


    public function sortDetail()
    {
        $meet_id = input('meet_id');
        $model = MeetModel::get($meet_id);
        if (!$model) {
            $this->error('会议不存在');
        }
        $this->success('成功',['set_sort' => $model['set_sort']]);
    }

    // 详情
    public function userdetail()
    {
        $user = $this->auth->getUser();
        $meet_id = input('meet_id');
        $map = [
            'meet_id' => $meet_id,
            'user_id' => $user['id'],
        ];
        $info = MeetTopicModel::where($map)->find();
        if(empty($info)){
            $this->success('成功',[]);
        }
        $type = ['topic'];
        if($info['status'] == 1){
            $type = ['topic','vote'];
        }
        $checkList= MeetCheckModel::where("topic_id", "in", $info['id'])
            ->where('type','in',$type)
            ->field("status,user_id,content,files,createtime")
            ->order("id desc")
            ->select();
        $info['user'] = [
            'avatar' => $user['avatar'],
            'nickname' => $user['nickname']
        ];
        foreach ( $checkList  as $k => &$val) {
            $user = \app\common\model\User::get($val['user_id']);
            $username = $user ? $user['nickname'] : '';
            $check_status = $val['status'] == 1 ? '通过' : '驳回';
            $val['check_text'] = $username . $check_status;
            $val['check_status'] = $val['status'];
            $val['status_name'] = $val['status'] ? "同意" : "不同意";
            //$val['createtime'] = date("Y-m-d H:i:s",$val['createtime']);
            if (!empty($val['files'])) {
                $val['files'] = json_decode(str_replace('&quot;', '"', $val['files']), true);
            } else {
                $val['files'] = [];
            }
        }
        if(empty($checkList)){
            $checkList = [
                ['status' => 2,'check_text' => '待审核','content' => '','createtime_text' => date('Y-m-d H:i',$info['createtime'])]
            ];
        }
        if($info['status'] == 2 && !empty($checkList)){
            $checkList = collection($checkList)->toArray();
            array_push($checkList, ['status' => 0,'check_text' => '已提交，等待审核','content' => '','createtime_text' => date('Y-m-d H:i',$info['updatetime'])]);
        }
        $info['check_lis'] = $checkList;
        $this->success('成功', $info);
    }


    // 详情
    public function detail()
    {
        $input = input();
        $user = $this->auth->getUser();
        $input['user_id'] = $this->auth->id;
        $input['nickname'] = $user['nickname'];
        $info = MeetTopicModel::detail($input);
        $this->success('成功', $info);
    }

    // 详情
    public function editdetail()
    {
        $user = $this->auth->getUser();
        $id = input('id');
        $info = MeetTopicModel::get($id);
        if(empty($info)){
            $this->success('成功',[]);
        }
        $type = ['topic'];
        if($info['status'] == 1){
            $type = ['topic','vote'];
        }
        $checkList= MeetCheckModel::where("topic_id", "in", $info['id'])
            ->where('type','in',$type)
            ->field("status,user_id,content,files,createtime")
            ->order("id desc")
            ->select();
        $info['user'] = [
            'avatar' => $user['avatar'],
            'nickname' => $user['nickname']
        ];
        foreach ( $checkList  as $k => &$val) {
            $user = \app\common\model\User::get($val['user_id']);
            $username = $user ? $user['nickname'] : '';
            $check_status = $val['status'] == 1 ? '通过' : '驳回';
            $val['check_text'] = $username . $check_status;
            $val['check_status'] = $val['status'];
            $val['status_name'] = $val['status'] ? "同意" : "不同意";
            //$val['createtime'] = date("Y-m-d H:i:s",$val['createtime']);
            if (!empty($val['files'])) {
                $val['files'] = json_decode(str_replace('&quot;', '"', $val['files']), true);
            } else {
                $val['files'] = [];
            }
        }
        if(empty($checkList)){
            $checkList = [
                ['status' => 2,'check_text' => '待审核','content' => '','createtime_text' => date('Y-m-d H:i',$info['createtime'])]
            ];
        }
        if($info['status'] == 2 && !empty($checkList)){
            $checkList = collection($checkList)->toArray();
            array_push($checkList, ['status' => 0,'check_text' => '已提交，等待审核','content' => '','createtime_text' => date('Y-m-d H:i',$info['updatetime'])]);
        }
        $info['check_lis'] = $checkList;
        $this->success('成功', $info);
    }

    /**
     * 设置课题截止时间
     * @throws \think\exception\DbException
     */
    public function setPlanOffTime(){
        try {
            $input = input();
            $meetId = $input['meet_id'];
            $meetInfo = MeetModel::get($meetId);
            $planOffTime = $input['plan_off_time']??0;
            if(!$meetInfo){
                throw new Exception('会议不存在');
            }
            if(!empty($input['plan_off_time'])){
                $planOffTime = strtotime($input['plan_off_time']);
            }
            $meetInfo->plan_off_time = $planOffTime;
            $meetInfo->save();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('设置成功', []);

    }

    public function add()
    {
        $user = $this->auth->getUser();
        $input = input();
        $meet_id = input('meet_id');
        $meet = MeetModel::get($meet_id);
        if (!$meet) {
            $this->error('会议不存在');
        }

        if (time() > $meet['topic_submit_off_time']) {
            $this->error('议题上传时间已截至');
        }

        if (empty($input['content'])) {
            $this->error('请填写议题内容');
            return;
        }
        if(!empty($input['images'])){
            $input['images'] = htmlspecialchars_decode($input['images']);
        }
        if(!empty($input['files'])){
            $input['files'] = htmlspecialchars_decode($input['files']);
        }
        /*$checkRole = MeetModel::checkActionRole($meet,$this->auth->id,'attend_topic');
        if($checkRole['status'] == 0 ){
            $this->error($checkRole['msg']);
        }*/
        $input['status'] = 2;
        $input['nickname'] = $user['nickname'];
        $id = (int)input('id');
        $map = [
            //'meet_id' => $input['meet_id'],
            'id' => $id,
        ];
        $res = MeetTopicModel::where($map)->find();
        if ($res) {
            $model = new MeetTopicModel();
            $row = $model->allowField(true)->save($input,['id'=> $res['id']]);
            $input['topic_id'] = $res['id'];
            $input['user_id'] = $this->auth->id;
            $meet->is_yiti = 1;
            $meet->save();
            $info = MeetNoticeModel::sendMeetNotice($input,"topic_add",$meet);
            $this->success($info['msg'], $info);
        } else {
            $input['user_id'] = $this->auth->id;
            $model = new MeetTopicModel($input);
            $row = $model->allowField(true)->save();
            $input['topic_id'] = $model->getLastInsID();
            $info = MeetNoticeModel::sendMeetNotice($input,"topic_add",$meet);
            $meet->is_yiti = 1;
            $meet->save();
            $this->success($info['msg'], $info);
        }

        $this->success('添加成功', $row);
    }

    public function edit()
    {
        $input = input();
        $id = input('id');
        $model = MeetTopicModel::get($id);
        if (!$model) {
            $this->error('会议议题不存在');
        }
        $meet_id = $model['meet_id'];
        $meet = MeetModel::get($meet_id);
        if (!$meet) {
            $this->error('会议不存在');
        }
        if(!empty($input['images'])){
            $input['images'] = htmlspecialchars_decode($input['images']);
        }
        if(!empty($input['files'])){
            $input['files'] = htmlspecialchars_decode($input['files']);
        }
        $user = $this->auth->getUserinfo();
        $input['status'] = 2;
        $model = new MeetTopicModel();
        $row = $model->allowField(true)->save($input, ['id' => $input['id']]);

        $input['nickname'] = $user['nickname'];
        $input['topic_id'] = $input['id'];
        $input['user_id'] = $this->auth->id;
        $meet->is_yiti = 1;
        $meet->save();
        $info = MeetNoticeModel::sendMeetNotice($input,"topic_add",$meet);

        $this->success('修改成功', $row);
    }

    public function delete()
    {
        $input = input();
        $model = new MeetTopicModel();
        $row = $model->where(['id' => $input['id'], 'user_id' => $this->auth->id])->delete();
        if ($row) {
            $this->success('删除成功', $row);
        } else {
            $this->error('删除失败');
        }
    }

    public function excel()
    {
        if(empty(input('meet_id'))){
            $this->error('meet_id必传');
        }
        $meet_id = input('meet_id');
        $model = MeetModel::get($meet_id);
        if (!$model) {
            $this->error('会议不存在');
        }
        $list = TopicTopModel::saveUser2($model);
        $new = [];
        $i=0;
        foreach($list as &$v){
            $map = [
                'meet_id' => input('meet_id'),
                'user_id' => $v['user_id'],
            ];
            $lists = MeetTopicModel::getUserlist2($map);
            $v['list'] = $lists;
            if(!empty($lists)){
                foreach($lists as $k=>$vv){
                    //echo $i.PHP_EOL;
                    $new[$i] = $vv;
                    $i++;
                }
            }
        }
        $List = $new;
        $newExcel = new \PhpOffice\PhpSpreadsheet\Spreadsheet();  //创建一个新的excel文档
        $newExcel->getActiveSheet()->setTitle($model['title'].'-议题');  //获取当前操作sheet的对象
        $newExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '议题提交人')
            ->setCellValue('B1', '议题内容')
            //->setCellValue('C1', '议题审核人')
            ->setCellValue('C1', '议题审核意见');
            //->setCellValue('E1', '');
        foreach ($List as $k => $val) {
            $k = $k + 2;
            $newExcel->getActiveSheet()->setCellValue('A' . $k, $val['user']['nickname'])
                ->setCellValue('B' . $k, $val['content'])
                //->setCellValue('C' . $k, $val['check_nickname'])
                ->setCellValue('C' . $k, $val['check_status']);
                //->setCellValue('E' . $k, date("Y-m-d H:i:s", $val['createtime']));
        }
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($newExcel, 'Xlsx');
        $filename = 'yiti'.$meet_id.'.Xlsx';
        $path = '/uploads/'.date('Ymd');
        if (!file_exists('.'.$path)) {
            mkdir('.'.$path,0777, true);
        }
        $filePath = $path.'/' . $filename;
        $writer->save('.'.$filePath);
        $url = request()->domain().$filePath;
        $size = filesize('./'.$filePath);
        $file_name = $filename;
        $data = [
            'filesize' => $size,
            'filename' => $file_name,
            "fullurl" => $url,
        ];
        $this->success('成功',$data);
    }

}
